<template>
  <div v-if="isShow" class="graph">
    <!-- <p class="graph-title">筛选条件:</p> -->
    <div class="graph-container" v-if="optsMap">
      <div
        v-for="(group, group_i) in list"
        :key="`group_${group_i}`"
        class="group"
      >
        <div
          class="group-content"
          :class="{
            'group-content-last': group_i == list.length - 1,
          }"
        >
          <div
            v-for="(item, item_i) in group"
            :key="`item_${item_i}`"
            class="item"
          >
            <div
              class="item-content"
              :class="{ 'item-content-last': item_i === group.length - 1 }"
            >
              <template v-if="item.key && item.value">
                <span v-if="optsMap[item.key]?.label">{{
                  optsMap[item.key].label
                }}</span>
                <span v-else class="item-content-error"
                  >未知字段（{{ item.key }}）</span
                >
                <span>{{ matcherMap[item.matcher] }}：</span>
                <span>{{ getItemValue(item) }}</span>
              </template>
              <template v-else>
                <span>{{ item.key }}</span>
              </template>
              <span
                v-if="group.length > 1"
                class="item-content-close"
                @click="removeItem(group_i, item_i)"
              ></span>
              <div
                v-if="item_i !== group.length - 1"
                class="item-content-logic"
              >
                <div class="item-content-logic-text">
                  {{ logicMap[item['logic']] }}
                </div>
                <div class="item-content-logic-line"></div>
              </div>
            </div>
          </div>
        </div>
        <div class="group-del" @click="removeGroup(group_i)"></div>
        <div v-if="group_i !== list.length - 1" class="group-logic">
          {{ logicMap[group['logic']] }}
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { logicMap, matcherMap } from '../common';
import AdvancedSearch from '../AdvancedSearch';
import { defineProps, defineEmits, watch, ref, onMounted } from 'vue';
import { useStore } from 'vuex';
const emit = defineEmits(['advancedSearch']);
const store = useStore();
const props = defineProps({
  searchText: {
    type: String,
    default: '',
  },
  category: {
    type: String,
    default: '',
  },
});
const isShow = ref(false);
const list = ref<any>([]);
const optsMap = ref<any>(null);
onMounted(() => {
  setOpts();
});
const update = () => {
  if (AdvancedSearch.isTemplateStr(props.searchText)) {
    list.value = AdvancedSearch.parse2Arr(props.searchText);
    isShow.value = true;
  } else {
    isShow.value = false;
  }
};
watch(
  () => props.searchText,
  (newValue, oldValue) => {
    update();
  },
  {
    immediate: true,
  },
);
const advancedSearchOptss = async () => {
  await store.dispatch('expose/setAdvancedSearchOpts');
};
const setOpts = async () => {
  advancedSearchOptss().then(() => {
    const advancedSearchOpts: any = store.state.expose.advancedSearchOpts;
    const map: any = {};
    if (typeof advancedSearchOpts === 'object' && advancedSearchOpts !== null) {
      const values = Object.values(advancedSearchOpts) as any[];
      values
        .reduce((acc, val) => acc.concat(val), [])
        .forEach((el: any) => {
          map[el.signValue] = el;
        });
      optsMap.value = map;
    }
  });
};

// 转义成字符串
const arr2Str = () => {
  const lists = list.value;
  if (!lists.length) {
    return '';
  }
  let templateStr = '';
  for (let i = 0; i < lists.length; i++) {
    const group = lists[i];
    let groupStr = '';
    for (let i2 = 0; i2 < group.length; i2++) {
      const item = group[i2];
      if (i2 === group.length - 1) {
        item.logic = '';
      }
      groupStr += `${item.key}${item.matcher}${item.value}${item.logic || ''}`;
    }
    groupStr = `(${groupStr})`;
    if (i === lists.length - 1) {
      lists[i].logic = '';
    }
    templateStr += `${groupStr}${lists[i].logic || ''}`;
  }
  return templateStr;
};

// 重新查询
const toSearch = async () => {
  let str = arr2Str();
  emit('advancedSearch', str);
};
// 清除条件组
const removeGroup = (groupIndex) => {
  list.value.splice(groupIndex, 1);
  toSearch();
};
// 清除条件项
const removeItem = (groupIndex, itemIndex) => {
  list.value[groupIndex].splice(itemIndex, 1);
  toSearch();
};
// 获取条件项的值
const getItemValue = (item) => {
  // 获取项的配置
  const opt = optsMap.value[item.key];
  const value = item.value.slice(1, -1); // 去掉拼接的双引号
  if (opt?.inputType === 'selection') {
    const v = opt.selection.find((el) => el.value === value);
    if (v.label) return v.label;
  }
  return item.value || '';
};
</script>
<style lang="scss" scoped>
.graph {
  width: 100%;
  margin-top: 10px;
  &-title {
    margin-bottom: 10px;
    font-family: SourceHanSansCN-Medium;
    font-size: 12px;
    color: $-v-color-white;
  }
  &-container {
    display: flex;
    flex-wrap: wrap;
    .group {
      margin-bottom: 10px;
      display: flex;
      align-items: center;
      &-content {
        box-sizing: border-box;
        max-width: calc(100% - 90px);
        padding: 0 8px;
        height: 100%;
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        flex: 0 0 auto;
        min-height: 40px;
        box-sizing: border-box;
        // color: #8590b3;
        // background: rgba(0, 0, 0, 0.1);
        border: 1px solid rgb(220, 223, 230);

        &-last {
          max-width: calc(100% - 40px);
        }
        .item {
          max-width: 100%;
          display: flex;
          align-items: center;
          flex: 0 0 auto;
          &-content {
            position: relative;
            box-sizing: border-box;
            max-width: calc(100% - 36px);
            flex: 0 0 auto;
            margin: 8px 0;
            margin-right: 36px;
            padding: 0 8px;
            min-height: 26px;
            font-size: 12px;
            font-weight: 500;
            line-height: 26px;
            // background: rgba(133, 144, 179, 0.1);
            word-break: break-all;

            &-last {
              margin-right: 8px;
              max-width: calc(100% - 8px);
            }
            &-logic {
              position: absolute;
              top: 50%;
              right: -28px;
              width: 20px;
              height: 20px;
              background: #5c637b;
              border-radius: 50%;
              transform: translateY(-50%);
              &-text {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%) scale(0.5);
                font-size: 20px;
                color: #fff;
                z-index: 1;
              }
              &-line {
                position: absolute;
                top: 50%;
                left: 50%;
                width: 36px;
                height: 1px;
                background: #5c637b;
                transform: translate(-50%, -50%);
              }
            }
            &-close {
              margin-left: 9px;
              display: inline-block;
              width: 14px;
              height: 14px;
              line-height: 26px;
              background: url(../images/group-close.jpg) no-repeat center;
              background-size: 100%;
              border-radius: 50%;
              vertical-align: middle;
              cursor: pointer;
            }
            &-error {
              color: #d8421a;
              // background: rgba(97, 99, 21, 0.25);
              display: inline-block;
              border-radius: 2px;
              padding-left: 4px;
            }
          }
        }
      }

      &-del {
        box-sizing: border-box;
        width: 40px;
        height: 100%;
        background: url(../images/item-close.png) no-repeat center;
        background-size: 14px 14px;
        border: 1px solid rgb(220, 223, 230);
        border-left: none;
        cursor: pointer;
      }
      &-logic {
        margin: 0 10px;
        width: 30px;
        height: 30px;
        font-size: 14px;
        line-height: 30px;
        text-align: center;
        color: #fff;
        background: #5c637b;
        border-radius: 50%;
      }
    }
  }
}
</style>
